<script setup lang="ts" name="DictTag">
import { PropType, computed } from 'vue'
import { isHexColor } from '@/utils/color'
import { ElTag } from 'element-plus'
import { DictDataType, getDictOptions } from '@/utils/dict'
import { isArray, isString, isNumber, isBoolean } from '@/utils/is'
const props = defineProps({
  type: {
    type: String as PropType<string>,
    required: true
  },
  value: {
    type: [String, Number, Boolean, Array],
    required: true
  },
  // 字符串分隔符 只有当 props.value 传入值为字符串时有效
  separator: {
    type: String as PropType<string>,
    default: ','
  },
  // 每个 tag 之间的间隔，默认为 5px，参考的 el-row 的 gutter
  gutter: {
    type: String as PropType<string>,
    default: '5px'
  }
})

const dictOptions = getDictOptions(props.type)
const valueArr: any = computed(() => {
  let res: string[] = []
  const result: DictDataType[] = []
  // 1. 是 Number 类型和 Boolean 类型的情况
  if (isNumber(props.value) || isBoolean(props.value)) {
    res = [String(props.value)]
  }
  // 2. 是字符串（进一步判断是否有包含分隔符号 -> props.sepSymbol ）
  else if (isString(props.value)) {
    res = (props.value as string).split(props.separator)
  }
  // 3. 数组
  else if (isArray(props.value)) {
    res = (props.value as Array<any>).map(String)
  }
  if (res.length > 0) {
    dictOptions.map((dict: DictDataType) => {
      if (res.includes(String(dict.value))) {
        if (dict.colorType + '' === 'primary' || dict.colorType + '' === 'default') {
          dict.colorType = ''
        }
        result.push(dict)
      }
    })
    return result
  } else {
    return []
  }
})
</script>

<template>
  <div v-if="valueArr.length > 0 && type && value !== undefined && value !== null && value !== ''" class="dict-tag" :style="{display: 'inline-flex', gap: props.gutter, justifyContent: 'center', alignItems: 'center'}">
    <ElTag v-for="(dict, index) in valueArr" :key="index" :style="{color: dict.cssClass ? '#fff' : '' }" :type="dict.colorType || null" :color="dict.cssClass && isHexColor(dict.cssClass) ? dict.cssClass : ''" :disableTransitions="true">{{ dict.label }}</ElTag>
  </div>
</template>

<style scoped lang="scss"></style>
